<template>
	<view class="confirm-order-container">
		<!-- 头部 -->
		<view class="order-header">
			<text class="header-title">确认订单</text>
		</view>

		<!-- 主要内容 -->
		<view class="order-content">
			<!-- 收货地址 -->
			<view class="address-section" @click="showAddressList">
				<view class="section-title">收货地址</view>
				<view class="address-content" v-if="selectedAddress">
					<view class="address-info">
						<text class="name">{{selectedAddress.name}}</text>
						<text class="phone">{{selectedAddress.phoneNum}}</text>
					</view>
					<text class="address-detail">{{selectedAddress.content}}</text>
				</view>
				<view class="no-address" v-else>
					<text>请选择收货地址</text>
				</view>
			</view>

			<!-- 商品列表 -->
			<view class="goods-section">
				<view class="section-title">商品信息</view>
				<view class="goods-list">
					<view class="goods-item" v-for="(item, index) in checkoutItems" :key="index">
						<image class="goods-image" :src="'http://localhost:3000/'+item.productImg" mode="aspectFill"></image>
						<view class="goods-info">
							<text class="goods-name">{{item.productName}}</text>
							<view class="goods-price">
								<text class="price">¥{{item.price}}</text>
								<text class="quantity">x{{item.num}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 订单金额 -->
			<view class="order-summary">
				<view class="summary-item">
					<text>商品合计</text>
					<text>¥{{totalPrice.toFixed(2)}}</text>
				</view>
				<view class="summary-item">
					<text>运费</text>
					<text>¥0.00</text>
				</view>
				<view class="summary-total">
					<text>实付金额</text>
					<text class="price">¥{{totalPrice.toFixed(2)}}</text>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-btn" @click="submitOrder">提交订单</view>
		</view>

		<!-- 地址列表弹窗 -->
		<view class="modal-mask" v-if="showAddressModal" @click="hideAddressModal"></view>
		<view class="address-modal" v-if="showAddressModal">
			<view class="modal-header">
				<text>选择收货地址</text>
				<text class="close-btn" @click="hideAddressModal">×</text>
			</view>
			<scroll-view class="address-list" scroll-y>
				<view class="address-item" v-for="(item, index) in addressList" :key="index"
					@click="selectAddress(item)">
					<view class="address-info">
						<text class="name">{{item.name}}</text>
						<text class="phone">{{item.phoneNum}}</text>
					</view>
					<text class="address-detail">{{item.content}}</text>
					<view class="address-actions">
						<text class="edit-btn" @click.stop="editAddress(index)">编辑</text>
						<text class="delete-btn" @click.stop="deleteAddress(index)">删除</text>
					</view>
				</view>
				<view class="add-address-btn" @click="showEditModal('add')">
					<text>+ 添加新地址</text>
				</view>
			</scroll-view>
		</view>

		<!-- 地址编辑弹窗 -->
		<view class="modal-mask" v-if="showEditAddressModal" @click="hideEditModal"></view>
		<view class="edit-modal" v-if="showEditAddressModal">
			<view class="modal-header">
				<text>{{editType === 'add' ? '新增地址' : '编辑地址'}}</text>
			</view>
			<view class="form-item">
				<text class="label">收货人</text>
				<input class="input" v-model="editForm.name" placeholder="请输入收货人姓名" />
			</view>
			<view class="form-item">
				<text class="label">手机号</text>
				<input class="input" v-model="editForm.phoneNum" placeholder="请输入手机号码" type="number" />
			</view>
			<view class="form-item">
				<text class="label">详细地址</text>
				<input class="input" v-model="editForm.content" placeholder="请输入详细地址" />
			</view>
			<view class="modal-footer">
				<view class="btn cancel" @click="hideEditModal">取消</view>
				<view class="btn confirm" @click="saveAddress">保存</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				checkoutItems: [], // 购物车选中商品
				selectedAddress: null, // 选中的地址
				addressList: [], // 地址列表
				totalPrice: 0, // 订单总价

				// 弹窗控制
				showAddressModal: false, // 显示地址列表
				showEditAddressModal: false, // 显示编辑地址
				editType: 'add', // 编辑类型 add/edit
				editForm: { // 编辑表单
					name: '',
					phoneNum: '',
					content: '',
					id: ''
				}
			}
		},
		onLoad() {
			this.loadCheckoutItems();
			this.loadAddressList();
		},
		methods: {
			// 加载购物车选中商品
			loadCheckoutItems() {
				const items = uni.getStorageSync('checkoutItems') || [];
				if (items.length > 0) {
					this.checkoutItems = items;
					this.calculateTotal();
				} else {
					uni.showToast({
						title: '没有选中商品',
						icon: 'none'
					});
					setTimeout(() => uni.navigateBack(), 1500);
				}
			},

			// 计算总价
			calculateTotal() {
				this.totalPrice = this.checkoutItems.reduce((total, item) => {
					return total + (item.price * item.num);
				}, 0);
			},

			// 加载地址列表
			loadAddressList() {
				uni.showLoading({
					title: '加载中...'
				});

				uni.request({
					url: 'http://localhost:8081/api/user/address/getList',
					method: 'POST',
					header: {
						'Content-Type': 'application/json',
						'Authorization': 'Bearer ' + uni.getStorageSync('token')
					},
					data: {
						user_id: uni.getStorageSync('userInfo').user_id
					},
					success: (res) => {
						uni.hideLoading();
						if (res.data.code === '001') {
							this.addressList = res.data.data;
							if (this.addressList.length > 0) {
								this.selectedAddress = this.addressList[0];
							}
						} else {
							uni.showToast({
								title: res.data.msg || '获取地址失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
						console.error(err);
					}
				});
			},

			// 显示地址列表
			showAddressList() {
				this.showAddressModal = true;
			},

			// 隐藏地址列表
			hideAddressModal() {
				this.showAddressModal = false;
			},

			// 选择地址
			selectAddress(item) {
				this.selectedAddress = item;
				this.hideAddressModal();
			},

			// 显示编辑弹窗
			showEditModal(type, index = -1) {
				this.editType = type;
				if (type === 'edit') {
					this.editForm = {
						name: this.addressList[index].name,
						phoneNum: this.addressList[index].phoneNum,
						content: this.addressList[index].content,
						id: this.addressList[index].id
					};
				} else {
					this.editForm = {
						name: '',
						phoneNum: '',
						content: '',
						id: ''
					};
				}
				this.hideAddressModal();
				this.showEditAddressModal = true;
			},

			// 隐藏编辑弹窗
			hideEditModal() {
				this.showEditAddressModal = false;
			},

			// 编辑地址
			editAddress(index) {
				this.showEditModal('edit', index);
			},

			// 删除地址
			deleteAddress(index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除该地址吗？',
					success: (res) => {
						if (res.confirm) {
							uni.request({
								url: 'http://localhost:8081/api/user/address/deleteAddress',
								method: 'POST',
								header: {
									'Content-Type': 'application/json',
									'Authorization': 'Bearer ' + uni.getStorageSync('token')
								},
								data: {
									id: this.addressList[index].id
								},
								success: (res) => {
									if (res.data.code === '001') {
										this.addressList.splice(index, 1);
										uni.showToast({
											title: '删除成功',
											icon: 'success'
										});

										// 如果删除的是当前选中的地址，清空选中
										if (this.selectedAddress && this.selectedAddress.id ===
											this.addressList[index]?.id) {
											this.selectedAddress = null;
										}
									} else {
										uni.showToast({
											title: res.data.msg || '删除失败',
											icon: 'none'
										});
									}
								},
								fail: (err) => {
									uni.showToast({
										title: '网络请求失败',
										icon: 'none'
									});
									console.error(err);
								}
							});
						}
					}
				});
			},

			// 保存地址
			saveAddress() {
				if (!this.editForm.name) {
					uni.showToast({
						title: '请输入收货人姓名',
						icon: 'none'
					});
					return;
				}

				if (!this.editForm.phoneNum || !/^1[3-9]\d{9}$/.test(this.editForm.phoneNum)) {
					uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none'
					});
					return;
				}

				if (!this.editForm.content) {
					uni.showToast({
						title: '请输入详细地址',
						icon: 'none'
					});
					return;
				}

				const apiUrl = this.editType === 'add' ?
					'http://localhost:8081/api/user/address/addAddress' :
					'http://localhost:8081/api/user/addresss/updateAddress';

				const requestData = this.editType === 'add' ?
					{
						name: this.editForm.name,
						phoneNum: this.editForm.phoneNum,
						content: this.editForm.content,
						user_id: uni.getStorageSync('userInfo').user_id
					} :
					{
						name: this.editForm.name,
						phoneNum: this.editForm.phoneNum,
						content: this.editForm.content,
						id: this.editForm.id
					};

				uni.showLoading({
					title: '保存中...'
				});

				uni.request({
					url: apiUrl,
					method: 'POST',
					header: {
						'Content-Type': 'application/json',
						'Authorization': 'Bearer ' + uni.getStorageSync('token')
					},
					data: requestData,
					success: (res) => {
						uni.hideLoading();
						if (res.data.code === '001') {
							this.loadAddressList();
							this.hideEditModal();
							uni.showToast({
								title: '保存成功',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: res.data.msg || '保存失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
						console.error(err);
					}
				});
			},

			// 提交订单
			submitOrder() {
				if (!this.selectedAddress) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					});
					return;
				}

				uni.showLoading({
					title: '提交中...'
				});

				uni.request({
					url: 'http://localhost:8081/api/user/order/addOrder',
					method: 'POST',
					header: {
						'Content-Type': 'application/json',
						'Authorization': 'Bearer ' + uni.getStorageSync('token')
					},
					data: {
						user_id: uni.getStorageSync('userInfo').user_id,
						products: this.checkoutItems,
						status: '1',
						addressId: this.selectedAddress.id
					},
					success: (res) => {
						uni.hideLoading();
						if (res.data.code === '001') {
							// 从购物车移除已购买商品
							this.removePurchasedItems();

							uni.showToast({
								title: '订单提交成功',
								icon: 'success'
							});

							setTimeout(() => {
								uni.redirectTo({
									url: '/pages/order/order'
								});
							}, 1500);
						} else {
							uni.showToast({
								title: res.data.msg || '提交订单失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
						console.error(err);
					}
				});
			},

			// 从购物车移除已购买商品
			removePurchasedItems() {
				const cartItems = uni.getStorageSync('cartItems') || [];
				const purchasedIds = this.checkoutItems.map(item => item.id);
				const newCartItems = cartItems.filter(item => !purchasedIds.includes(item.id));
				uni.setStorageSync('cartItems', newCartItems);
				uni.removeStorageSync('checkoutItems');
			}
		}
	}
</script>

<style>
	/* 基础样式 */
	.confirm-order-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 100rpx;
	}

	.order-header {
		background-color: #fff;
		padding: 30rpx;
		text-align: center;
		border-bottom: 1rpx solid #eee;
	}

	.header-title {
		font-size: 36rpx;
		font-weight: bold;
	}

	.order-content {
		padding: 20rpx;
	}

	/* 地址部分 */
	.address-section {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 25rpx;
		margin-bottom: 20rpx;
	}

	.section-title {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.address-content {
		padding-top: 15rpx;
	}

	.address-info {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.address-info .name {
		font-size: 32rpx;
		font-weight: bold;
		margin-right: 30rpx;
	}

	.address-info .phone {
		font-size: 28rpx;
		color: #666;
	}

	.address-detail {
		font-size: 28rpx;
		color: #666;
		line-height: 1.5;
	}

	.no-address {
		padding: 30rpx 0;
		text-align: center;
		color: #999;
	}

	/* 商品部分 */
	.goods-section {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 25rpx;
		margin-bottom: 20rpx;
	}

	.goods-list {
		margin-top: 20rpx;
	}

	.goods-item {
		display: flex;
		padding: 25rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.goods-item:last-child {
		border-bottom: none;
	}

	.goods-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
	}

	.goods-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.goods-name {
		font-size: 28rpx;
		color: #333;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.goods-price {
		display: flex;
		justify-content: space-between;
		margin-top: 15rpx;
	}

	.goods-price .price {
		font-size: 30rpx;
		color: #e74c3c;
		font-weight: bold;
	}

	.goods-price .quantity {
		font-size: 26rpx;
		color: #999;
	}

	/* 订单汇总 */
	.order-summary {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 25rpx;
		margin-bottom: 20rpx;
	}

	.summary-item {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
		font-size: 28rpx;
		color: #666;
	}

	.summary-total {
		display: flex;
		justify-content: space-between;
		margin-top: 30rpx;
		padding-top: 20rpx;
		border-top: 1rpx dashed #eee;
		font-size: 30rpx;
		font-weight: bold;
	}

	.summary-total .price {
		color: #e74c3c;
	}

	/* 提交按钮 */
	.submit-btn {
		background-color: #e74c3c;
		color: #fff;
		font-size: 32rpx;
		text-align: center;
		padding: 25rpx;
		border-radius: 50rpx;
		margin-top: 30rpx;
	}

	/* 弹窗样式 */
	.modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 999;
	}

	.address-modal,
	.edit-modal {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		z-index: 1000;
		max-height: 70vh;
	}

	.edit-modal {
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 80%;
		border-radius: 20rpx;
		bottom: auto;
	}

	.modal-header {
		padding: 30rpx;
		border-bottom: 1rpx solid #eee;
		font-size: 32rpx;
		font-weight: bold;
		text-align: center;
		position: relative;
	}

	.close-btn {
		position: absolute;
		right: 30rpx;
		top: 30rpx;
		font-size: 40rpx;
		color: #999;
	}

	.address-list {
		max-height: 60vh;
		padding: 0 30rpx;
		overflow-y: auto;
	}

	.address-item {
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.address-item:last-child {
		border-bottom: none;
	}

	.address-actions {
		display: flex;
		justify-content: flex-end;
		margin-top: 20rpx;
	}

	.edit-btn,
	.delete-btn {
		font-size: 26rpx;
		padding: 8rpx 20rpx;
		border-radius: 6rpx;
		margin-left: 20rpx;
	}

	.edit-btn {
		color: #e74c3c;
		border: 1rpx solid #e74c3c;
	}

	.delete-btn {
		color: #999;
		border: 1rpx solid #999;
	}

	.add-address-btn {
		padding: 30rpx 0;
		text-align: center;
		color: #e74c3c;
		font-size: 30rpx;
	}

	/* 编辑表单 */
	.form-item {
		padding: 25rpx 30rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.label {
		display: block;
		margin-bottom: 15rpx;
		font-size: 28rpx;
		color: #333;
	}

	.input {
		width: 100%;
		font-size: 28rpx;
		padding: 15rpx 0;
	}

	.modal-footer {
		display: flex;
		padding: 30rpx 0;
	}

	.btn {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		font-size: 30rpx;
	}

	.btn.cancel {
		color: #666;
		border-right: 1rpx solid #eee;
	}

	.btn.confirm {
		color: #e74c3c;
		font-weight: bold;
	}
</style>